<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>
    PHP 单例模式 |
    
    无敌小笼包</title>
  
    <link rel="shortcut icon" href="/favicon.png">
  
  <link rel="stylesheet" href="/css/style.css">
  
    <link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">
  
  <script src="/js/pace.min.js"></script>
</head>

<body>
<main class="content">
  <section class="outer">
  <article id="post-phpsingerl" class="article article-type-post" itemscope itemprop="blogPost">

  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      PHP 单例模式
    </h1>
  

      </header>
    

    
      <div class="article-meta">
        <a href="/2016/05/10/phpsingerl/" class="article-date">
  <time datetime="2016-05-10T02:20:12.000Z" itemprop="datePublished">2016-05-10</time>
</a>
        
  <div class="article-category">
    <a class="article-category-link" href="/categories/Skill/">Skill</a>
  </div>

      </div>
    

    <div class="article-entry" itemprop="articleBody">
      
      
      
        <p> 数学与逻辑学中，singleton定义为“有且仅有一个元素的集合”<br>在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例，节省数据库开销<br><a id="more"></a></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div></pre></td><td class="code"><pre><div class="line">单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点，可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制，“阻止”所有想要生成对象的访问</div><div class="line"><span class="comment">/**</span></div><div class="line"> *     singleton Pattern 单例设计模式  3私1公</div><div class="line"> */</div><div class="line"> <span class="class"><span class="keyword">class</span> <span class="title">DB</span> </span></div><div class="line"> &#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> $_instance;<span class="comment">//保存类实例的私有静态成员变量</span></div><div class="line">    <span class="comment">//定义一个私有的构造函数，确保单例类不能通过new关键字实例化，只能被其自身实例化</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">()</span>//<span class="title">fai</span> <span class="title">nuo</span>最终 的  也就是后面的子类不能覆盖此方法</span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">echo</span> <span class="string">'test __construct'</span>;                                        </div><div class="line"><span class="comment">/*      final        -- 用于类、方法前。</span></div><div class="line">        final类   -- 不可被继承。</div><div class="line">        final方法 -- 不可被覆盖。        */</div><div class="line">    &#125;   </div><div class="line">    <span class="comment">//定义私有的__clone()方法，确保单例类不能被复制或克隆</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">__clone</span><span class="params">()</span> </span>&#123;&#125;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span><span class="params">()</span> </span></div><div class="line">    &#123;</div><div class="line">        <span class="comment">//检测类是否被实例化</span></div><div class="line">        <span class="keyword">if</span> (!(<span class="keyword">self</span>::$_instance <span class="keyword">instanceof</span> <span class="keyword">self</span>)) <span class="comment">//in s tens 奥复            </span></div><div class="line">        &#123;    <span class="comment">//在类里调用类的属性 要加$</span></div><div class="line">            <span class="comment">//（1）判断一个对象是否是某个类的实例，</span></div><div class="line">            <span class="comment">//（2）判断一个对象是否实现了某个接口。</span></div><div class="line">            <span class="keyword">self</span>::$_instance = <span class="keyword">new</span> DB();</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> <span class="keyword">self</span>::$_instance;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//调用单例类</span></div><div class="line">DB::getInstance();</div><div class="line">$db1=DB::getInstance();</div><div class="line">$db2=DB::getInstance();</div><div class="line">var_dump($db1);</div><div class="line">var_dump($db2);<span class="meta">&lt;?php</span></div><div class="line"><span class="comment">/**</span></div><div class="line"> *     singleton Pattern 单例设计模式  3私1公</div><div class="line"> */</div><div class="line"> <span class="class"><span class="keyword">class</span> <span class="title">DB</span> </span></div><div class="line"> &#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> $_instance;<span class="comment">//保存类实例的私有静态成员变量</span></div><div class="line">    <span class="comment">//定义一个私有的构造函数，确保单例类不能通过new关键字实例化，只能被其自身实例化</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">()</span>//<span class="title">fai</span> <span class="title">nuo</span>最终 的  也就是后面的子类不能覆盖此方法</span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">echo</span> <span class="string">'test __construct'</span>;</div><div class="line">    &#125;   </div><div class="line">    <span class="comment">//定义私有的__clone()方法，确保单例类不能被复制或克隆</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">__clone</span><span class="params">()</span> </span>&#123;&#125;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span><span class="params">()</span> </span></div><div class="line">    &#123;</div><div class="line">        <span class="comment">//检测类是否被实例化</span></div><div class="line">        <span class="keyword">if</span> (!(<span class="keyword">self</span>::$_instance <span class="keyword">instanceof</span> <span class="keyword">self</span>)) <span class="comment">//in s tens 奥复            </span></div><div class="line">        &#123;    <span class="comment">//在类里调用类的属性 要加$</span></div><div class="line">    <span class="comment">//（1）判断一个对象是否是某个类的实例，（2）判断一个对象是否实现了某个接口。</span></div><div class="line">            <span class="keyword">self</span>::$_instance = <span class="keyword">new</span> DB();</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> <span class="keyword">self</span>::$_instance;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//调用单例类</span></div><div class="line">DB::getInstance();</div><div class="line"></div><div class="line">$db1=DB::getInstance();</div><div class="line">$db2=DB::getInstance();</div><div class="line"></div><div class="line">var_dump($db1);</div><div class="line">var_dump($db2);</div></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://blog.mango16.cc/2016/05/10/phpsingerl/" data-id="cjrbtw1y600136d8hosnlhl0g"
         class="article-share-link">分享</a>
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Design-Pattern/">Design Pattern</a></li></ul>

    </footer>

  </div>

  
    
  <nav class="article-nav">
    
      <a href="/2016/06/05/monkeyKing/" class="article-nav-link">
        <strong class="article-nav-caption">前一篇</strong>
        <div class="article-nav-title">
          
            猴子选大王算法
          
        </div>
      </a>
    
    
      <a href="/2016/05/07/php工厂模式/" class="article-nav-link">
        <strong class="article-nav-caption">后一篇</strong>
        <div class="article-nav-title">PHP plant</div>
      </a>
    
  </nav>


  

  
    
  <div class="gitalk" id="gitalk-container"></div>
  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
  <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
  <script type="text/javascript">
      var gitalk = new Gitalk({
        clientID: 'caba8826a61790936307',
        clientSecret: '09a15037dcab30d9adf35a53ec6961939169f797',
        repo: 'm9rco.github.io',
        owner: 'm9rco',
        admin: ['m9rco'],
        // id: location.pathname,      // Ensure uniqueness and length less than 50
        id: md5(location.pathname),
        distractionFreeMode: false  // Facebook-like distraction free mode
      })

  gitalk.render('gitalk-container')
  </script>

  

</article>



</section>
  <footer class="footer">
  
  <div class="outer">
    <ul class="list-inline">
      <li>&copy; 2019 无敌小笼包</li>
      <i class="pulse"></i>
    </ul>
  </div>
</footer>

</main>
<aside class="sidebar">
  <button class="navbar-toggle"></button>

<nav class="navbar">
  
    <div class="logo">
      <a href="/"><img src="/images/hexo.svg" alt="无敌小笼包"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/">主页</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/archives">归档</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/gallery">相册</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/nagging">叽咕</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/about">关于</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="Search">
        <i class="fe fe-search"></i>
        搜索
      </a>
    </li>
  </ul>
</nav>

<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>

<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
</aside>
  <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/lazyload.min.js"></script>


  <script src="/fancybox/jquery.fancybox.min.js"></script>



  <script src="/js/search.js"></script>


<script src="/js/ocean.js"></script>

</body>
</html>